<template>
  <div
    class="drawpage"
    :style="{ backgroundImage: 'url(' + drawSettings.backgroundImage + ')' }"
  >
    <header>
      <a-space class="buttons">
        <div class="button" type="primary" @click="goToAdmin">管理界面</div>
        <div class="button" type="primary" @click="showPrizeModal = true">
          选择轮次
        </div>
      </a-space>
      <div class="current-prize-info">
        当前奖品：{{ currentPrize?.name || "请选择奖品" }}
      </div>
    </header>

    <!-- 奖品选择模态框 -->
    <a-modal
      v-model:open="showPrizeModal"
      title="选择抽奖轮次"
      ok-text="确定"
      cancel-text="取消"
      @ok="confirmPrizeSelect"
      width="500px"
    >
      <div class="prize-select-list">
        <div
          v-for="prize in prizeList"
          :key="prize.id"
          class="prize-item"
          :class="{ active: selectedPrize.id === prize.id }"
          @click="selectedPrize = prize"
          @dblclick="doSelectPrize(prize)"
        >
          <div class="prize-name">{{ prize.name }}</div>
          <div class="prize-info">
            <span>轮次：{{ prize.round }}</span>
            <span>数量：{{ prize.quantity }}</span>
          </div>
        </div>
        <div v-if="prizeList.length === 0" class="empty-prize">暂无奖品</div>
      </div>
    </a-modal>
    <div class="main-pannel lucky-pannel">
      <div class="prizetitle">{{ currentPrize?.name || "奖品加载中" }}</div>
      <div class="list">
        <div
          class="user"
          v-for="(item, index) in luckylist"
          :key="index"
          v-if="luckylist.length"
        >
          <div class="id">
            {{ item?.id }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, watch, onMounted, onUnmounted } from "vue";
import { baseApi, userApi, prizeApi } from "@/api/index.js";
import { useRoute, useRouter } from "vue-router";
import { message } from "ant-design-vue";

const route = useRoute();
const router = useRouter();

const loading = reactive({
  data: false,
});

// 活动的配置信息
const drawSettings = reactive({
  width: 1920,
  height: 1080,
  backgroundImage: "",
});

// 读取抽奖的配置信息
const fetchDrawSettings = async () => {
  try {
    const res = await baseApi.getSettings();
    drawSettings.backgroundImage = res?.data?.backgroundImage || "";
    console.log(drawSettings);
  } catch (error) {
    console.error("获取配置失败:", error);
  }
};
fetchDrawSettings();

// 读取轮次信息
const currentPrize = ref(null);
const prizeList = ref([]); // 奖品列表
const showPrizeModal = ref(false); // 奖品选择模态框显示状态
const selectedPrize = ref(null); // 选中的奖品ID

const fetchPrize = async () => {
  try {
    const res = await prizeApi.getList();
    prizeList.value = res.data.list || [];
    if (prizeList.value.length > 0) {
      currentPrize.value = prizeList.value[0];
      selectedPrize.value = prizeList.value[0];
    }
    console.log("奖品列表:", prizeList.value);
    console.log("当前奖品:", currentPrize.value);
  } catch (error) {
    console.error("获取奖品列表失败:", error);
    message.error("获取奖品列表失败", 0.4);
  }
};
fetchPrize();

const userlist = ref([]); // 中奖用户列表

// 监测屏幕变化
const resizeWindows = () => {};

// 加载抽奖用户信息
const fetchData = async () => {
  if (loading.data || !currentPrize.value) return;
  loading.data = true;
  try {
    const res = await userApi.getNonWinners({ page: 1, pagesize: 5000 }); // 获取未中奖用户
    console.log("用户列表:", res);
    userlist.value = res?.data.list || [];
    // 随机排序用户
    var randomNumber = function () {
      return 0.5 - Math.random();
    };
    userlist.value.sort(randomNumber);
  } catch (error) {
    console.error("获取用户列表失败:", error);
    message.error("获取用户列表失败", 0.4);
    userlist.value = [];
  } finally {
    loading.data = false;
  }
};

/**
 * 抽奖相关功能
 */
let rollTimer = null;
let rollIndex = 0;
const isEnd = ref(false);
const luckyNum = ref(5); // 抽的人数
const luckylist = ref([
  {
    id: 0,
    nickname: "loading",
  },
]); // 中奖用户列表
const luckyRound = ref(1); // 当前轮次
let rollTime = 30; // 滚动时间

watch(currentPrize, function (n) {
  // 重置数据
  rollIndex = 0;
  luckyRound.value = 1;
  isEnd.value = false;
  luckylist.value = [];
  luckyNum.value = currentPrize.value.quantity;
  fetchData();
  doRoll();
});

// 前往管理界面
const goToAdmin = () => {
  router.push("/admin");
};

// 奖品选择确认
const confirmPrizeSelect = () => {
  if (selectedPrize.value) {
    currentPrize.value = selectedPrize.value;
    showPrizeModal.value = false;
    message.success(`已选择：${selectedPrize.value.name}`, 0.4);
    // 重新加载用户数据
    fetchData();
  } else {
    message.error("请选择奖品", 0.4);
  }
};

const doSelectPrize = (prize) => {
  currentPrize.value = prize;
  showPrizeModal.value = false;
  // message.success(`已选择：p.name}`, 0.4);
  // 重新加载用户数据
  fetchData();
};

const doRoll = () => {
  rollTimer = setTimeout(function () {
    if (isEnd.value) return;
    // 当顺序轮完，重新打散
    if (rollIndex >= userlist.value.length - luckyNum.value) {
      rollIndex = 0;
      var randomNumber = function () {
        return 0.5 - Math.random();
      };
      userlist.value.sort(randomNumber);
    }
    luckylist.value = [];
    for (let index = 0; index < luckyNum.value; index++) {
      luckylist.value.push(userlist.value[rollIndex]);
      rollIndex++;
    }
    doRoll();
  }, rollTime);
};

doRoll();

const chkNum = (key) => {
  console.log(key.code);
  switch (key.code) {
    case "Enter":
      isEnd.value = true;
      saveData();
      break;
    case "Space":
      console.log("重新开始");
      isEnd.value = false;
      fetchData();
      doRoll();
      break;
    case "ControlLeft":
      showPrizeModal.value = !showPrizeModal.value;
      break;
    default:
      break;
  }
};
onMounted(() => {
  //侦听键盘事件
  document.addEventListener("keydown", chkNum);
});
onUnmounted(() => {
  if (rollTimer != null) clearTimeout(rollTimer);
  document.removeEventListener("keydown", chkNum);
});

// 保存中奖信息
const saveData = async () => {
  if (!currentPrize.value) {
    message.error("请先选择奖品", 0.4);
    return;
  }

  try {
    // 调用抽奖接口
    const res = await userApi.saveLucky({
      id: currentPrize.value.id,
      round: luckyRound.value,
      users: luckylist.value.map((item) => item?.id),
    });
    luckyRound.value++;
  } catch (error) {
    console.error("保存抽奖结果失败:", error);
    message.error("保存抽奖结果失败", 0.4);
  }
};
const resetData = () => {
  isEnd.value = false;
};

// 加密手机号
const encryMobile = (value) => {
  var reg = /(\d{3})\d{4}(\d{4})/;
  var phone = value.replace(reg, "$1****$2");
  return phone;
};
// 加密姓名
const encryName = (value) => {
  let len = value.length - 1;
  let hide = "";
  for (let i = 0; i < len; i++) {
    hide += "*";
  }
  var name = value.substring(0, 1) + hide;
  return name;
};
</script>

<style lang="less" scoped>
@import "Draw.less";

/* 头部奖品信息 */
.current-prize-info {
  position: absolute;
  right: 30px;
  top: 20px;
  background: rgba(255, 255, 255, 0.9);
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 18px;
  font-weight: bold;
  color: #1890ff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 奖品选择模态框样式 */
.prize-select-list {
  max-height: 400px;
  overflow-y: auto;
}

.prize-item {
  padding: 15px;
  margin-bottom: 10px;
  border: 2px solid #e8e8e8;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    border-color: #1890ff;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
  }

  &.active {
    border-color: #1890ff;
    background-color: #e6f7ff;
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.25);
  }
}

.prize-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.prize-info {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;

  span {
    padding: 2px 8px;
    background: #f0f0f0;
    border-radius: 4px;
  }
}

.empty-prize {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 16px;
}
</style>
